package cn.hxt.basic.controller;


import cn.hxt.basic.util.AjaxResult;
import cn.hxt.basic.util.FastDfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    /**
     * 上传
     * @param file
     * @return
     */
    @PostMapping
    public AjaxResult upload(@RequestPart(required = true,value = "File") MultipartFile file){
        try {

            //获取名字
            String filename = file.getOriginalFilename();
            //获取后缀                                               以点分割，取后一位
            String extName = filename.substring(filename.lastIndexOf(".") + 1);
            //                                       字节码文件    后缀
            String upload = FastDfsUtil.upload(file.getBytes(), extName);
            return AjaxResult.me().setResultObj(upload);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("操作失败了！！");
        }

    }


    /**
     * 删除
     * @param path
     * @return
     */
    @DeleteMapping  // post:/group1/M00/02/22/rBE3kWHNVcKAf1QKAAF-6xZ0lWg132.jpg
    public AjaxResult delete(@RequestParam String path){
        try {
            //从索引1开始截取
            String pathTmp = path.substring(1);
            //获取第一个/前的第一个（goup1）
            String groupName =  pathTmp.substring(0, pathTmp.indexOf("/")); //goup1
            //获取/之后的
            String fileName = pathTmp.substring(pathTmp.indexOf("/")+1);
            FastDfsUtil.delete(groupName, fileName);

            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("删除失败!!!");
        }
    }
}
